<template>
  <div class="sql-upload-form">
    <el-alert
      v-if="showSqlTip"
      title="SQL文件格式说明"
      type="info"
      description="支持标准的CREATE TABLE语句，包含表结构、字段定义、主键、外键等"
      show-icon
      :closable="false"
      class="tip-alert"
    />
    <el-upload
      ref="uploadRef"
      drag
      :auto-upload="false"
      :on-change="handleFileChange"
      :on-remove="handleFileRemove"
      :file-list="fileList"
      accept=".sql"
      class="upload-area"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将SQL文件拖到此处，或 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          只能上传 .sql 文件，且不超过10MB，复杂的sql文件请使用在线连接
        </div>
      </template>
    </el-upload>

    <div class="action-buttons">
      <el-button type="primary" :loading="loading" :disabled="!sqlContent" @click="handleGenerate">
        生成文档
      </el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles, UploadInstance } from 'element-plus'

interface Emits {
  (e: 'submit', sqlContent: string): void
}

const showSqlTip = ref(true)

const emit = defineEmits<Emits>()
const props = defineProps<{
  loading?: boolean
}>()

const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadFiles>([])
const sqlContent = ref<string>('')

const handleFileChange = (file: UploadFile) => {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      sqlContent.value = e.target?.result as string
    }
    reader.readAsText(file.raw)
  }
}

const handleFileRemove = () => {
  sqlContent.value = ''
}

const handleGenerate = () => {
  if (sqlContent.value) {
    emit('submit', sqlContent.value)
  }
}

const handleReset = () => {
  sqlContent.value = ''
  fileList.value = []
  uploadRef.value?.clearFiles()
}
</script>

<style scoped>
.sql-upload-form {
  max-width: 500px;
}

.upload-area {
  margin-bottom: 20px;
}

.action-buttons {
  text-align: center;
}
</style>
